import mxgraph from '@/utils/mxgraph'
import { mxIconSet, updateStyle } from '@/js/mxMethod.js'
const { mxEvent, mxRubberband, mxGraph, mxConstants, mxGraphModel, mxClient,
  mxUtils, mxImage, mxCellOverlay, mxGeometry, mxCell, mxCodec,
  mxPopupMenu, mxGraphHandler, mxConnectionHandler, mxRectangle } = mxgraph
const MxGraph = mxGraph
const MxRubberband = mxRubberband
const MxGraphModel = mxGraphModel
const MxImage = mxImage
const MxCellOverlay = mxCellOverlay
const MxCodec = mxCodec
const MxPopupMenu = mxPopupMenu

export default {

  methods: {
    //鼠标hover节点时，修改节点样式
    initHoverStyle(graph) {
      graph.addMouseListener(
        {
          currentState: null,
          previousStyle: null,
          mouseDown: function (sender, me) {
            if (this.currentState != null) {
              this.dragLeave(me.getEvent(), this.currentState);
              this.currentState = null;
            }
          },
          mouseMove: function (sender, me) {
            if (this.currentState != null && me.getState() == this.currentState) {
              return;
            }

            var tmp = graph.view.getState(me.getCell());

            // Ignores everything but vertices
            if (graph.isMouseDown || (tmp != null && !
              graph.getModel().isVertex(tmp.cell))) {
              tmp = null;
            }

            if (tmp != this.currentState) {
              if (this.currentState != null) {
                this.dragLeave(me.getEvent(), this.currentState);
              }

              this.currentState = tmp;

              if (this.currentState != null) {
                this.dragEnter(me.getEvent(), this.currentState);
              }
            }
          },
          mouseUp: function (sender, me) { },
          dragEnter: function (evt, state) {
            if (state != null) {
              this.previousStyle = state.style;
              state.style = mxUtils.clone(state.style);
              updateStyle(state, true);
              state.shape.apply(state);
              state.shape.redraw();

              if (state.text != null) {
                state.text.apply(state);
                state.text.redraw();
              }
            }
          },
          dragLeave: function (evt, state) {
            if (state != null) {
              state.style = this.previousStyle;
              updateStyle(state, false);
              state.shape.apply(state);
              state.shape.redraw();

              if (state.text != null) {
                state.text.apply(state);
                state.text.redraw();
              }
            }
          }
        });
    },
    //给节点增加hover的按钮
    initHoverIcons(graph) {
      // Defines the tolerance before removing the icons
      var iconTolerance = 20;

      // Shows icons if the mouse is over a cell
      graph.addMouseListener(
        {
          currentState: null, //当前cell的state
          currentIconSet: null,
          mouseDown: function (sender, me) {
            // Hides icons on mouse down
            if (this.currentState != null) {
              this.dragLeave(me.getEvent(), this.currentState);
              this.currentState = null;
            }
          },
          mouseMove: function (sender, me) {
            //避免离开单元格后微小的移动也会触发创建icon对象
            if (this.currentState != null && (me.getState() == this.currentState ||
              me.getState() == null)) {
              var tol = iconTolerance;
              var tmp = new mxRectangle(me.getGraphX() - tol,
                me.getGraphY() - tol, 2 * tol, 2 * tol);

              if (mxUtils.intersects(tmp, this.currentState)) {
                return;
              }
            }
            //判断是否要创建icons
            var tmp = graph.view.getState(me.getCell());

            // Ignores everything but vertices
            //if (graph.isMouseDown ) {
            if (graph.isMouseDown || (tmp != null && !graph.getModel().isVertex(tmp.cell))) {
              tmp = null;
            }
            //鼠标移出的情况
            if (tmp != this.currentState) {
              if (this.currentState != null) {
                this.dragLeave(me.getEvent(), this.currentState);
              }
              // 鼠标移入的情况
              this.currentState = tmp;

              if (this.currentState != null) {
                this.dragEnter(me.getEvent(), this.currentState);
              }
            }
          },
          mouseUp: function (sender, me) { },
          dragEnter: function (evt, state) {

            if (this.currentIconSet == null) {
              this.currentIconSet = new mxIconSet(state);
            }
          },
          dragLeave: function (evt, state) {
            if (this.currentIconSet != null) {
              this.currentIconSet.destroy();
              this.currentIconSet = null;
            }
          }
        });
    },
    //初始化连接节点
    initConnectEdge(graph) {
      // 显示导航线（红色虚线）
      mxGraphHandler.prototype.guidesEnabled = true
      // ctrl+拖拽复制流程图节点
      mxGraphHandler.prototype.cloneEnabled = false
      // 节点可连接
      graph.setConnectable(true)
      // 不允许无连接节点的edges
      graph.setAllowDanglingEdges(false)
      // 两个节点之间最多一条同方向连线
      graph.setMultigraph(true)
      mxConstants.DEFAULT_HOTSPOT = 1
      mxConstants.MIN_HOTSPOT_SIZE = 16
      mxConstants.HIGHLIGHT_COLOR = null
      graph.connectionHandler.connectImage = new MxImage('/images/connector.gif', 16, 16)
      // 连接线之后，修改线的id
      const mxConnectionHandlerInsertEdge = mxConnectionHandler.prototype.insertEdge
      graph.connectionHandler.insertEdge = function (parent, id, value, source, target, style) {
        var tranId = source.getId() + '-' + target.getId()
        var tranName = source.getValue() + '-' + target.getValue()
        arguments[1] = tranId
        arguments[2] = tranName
        arguments[5] = 'edge'
        return mxConnectionHandlerInsertEdge.apply(this, arguments)
      }
      //cell 上的label 是否可以拖动
      graph.edgeLabelsMovable = true
      graph.vertexLabelsMovable = false;

      // 重置连接图片的位置
      graph.connectionHandler.redrawIcons = function (icons, state) {
        if (icons != null && icons[0] != null && state != null) {
          var c = this.getIconPosition(icons[0], state)

          icons[0].bounds.x = c.x + state.width / 5 * 2
          icons[0].bounds.y = c.y
          icons[0].redraw()
        }
      }

    },
    //实现鼠标右键弹出菜单功能
    initPopupMenu(graph) {
      mxEvent.disableContextMenu(document.body);
      //控制最后一行的分割线是否显示
      graph.popupMenuHandler.smartSeparators = true
      // 鼠标滑过，二级菜单是否自动展开
      graph.popupMenuHandler.autoExpand = true;

      // Installs context menu
      graph.popupMenuHandler.factoryMethod = function (menu, cell, evt) {
        console.log(cell, 'cell', evt, 'evt')

        // shfit加鼠标左键或中间滚轮时不弹出右键菜单
        if (
          (mxEvent.isLeftMouseButton(evt) || evt.button === 4) &&
          mxEvent.isShiftDown(evt)
        ) {
          return
        }

        menu.addItem('Item 1', '/images/add.png', function () {
          alert('Item 1');
        });
        menu.addSeparator()
        menu.addItem('Item 2', null, function () {
          alert('Item 2');
        });

        menu.addSeparator();

        var submenu1 = menu.addItem('Submenu 1', null, null);

        menu.addItem('Subitem 1', null, function () {
          alert('Subitem 1');
        }, submenu1);
        menu.addItem('Subitem 1', null, function () {
          alert('Subitem 2');
        }, submenu1);
        menu.addSeparator()
      };
    },
    //查看graph的xml文件
    doExport2Console() {
      var enc = new MxCodec()
      var node = enc.encode(this.graph.getModel())
      var mxgraphXml = mxUtils.getPrettyXml(node)
      console.log(mxgraphXml)
    },
    //初始化节点的样式
    initStyle(graph) {
      var vStyle = graph.getStylesheet().getDefaultVertexStyle()

      var style = mxUtils.clone(vStyle)
      style[mxConstants.STYLE_FONTSIZE] = '12'
      style[mxConstants.STYLE_FONTCOLOR] = 'black'
      style[mxConstants.STYLE_STROKECOLOR] = 'black'
      style[mxConstants.STYLE_FILLCOLOR] = 'white'
      style[mxConstants.STYLE_GRADIENTCOLOR] = 'white'
      style[mxConstants.STYLE_GRADIENT_DIRECTION] = mxConstants.DIRECTION_EAST
      style[mxConstants.STYLE_ROUNDED] = true
      style[mxConstants.STYLE_SHADOW] = true
      style[mxConstants.STYLE_FONTSTYLE] = 1
      style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_LABEL
      style[mxConstants.STYLE_STROKECOLOR] = 'white'
      style[mxConstants.STYLE_ROUNDED] = true
      style[mxConstants.STYLE_SHADOW] = false
      style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER
      style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP
      style[mxConstants.STYLE_IMAGE_ALIGN] = mxConstants.ALIGN_CENTER
      style[mxConstants.STYLE_IMAGE_VERTICAL_ALIGN] = mxConstants.ALIGN_TOP
      style[mxConstants.STYLE_IMAGE] = '/images/start.png'
      style[mxConstants.STYLE_IMAGE_WIDTH] = '40'
      style[mxConstants.STYLE_IMAGE_HEIGHT] = '40'
      style[mxConstants.STYLE_SPACING_TOP] = '50'
      style[mxConstants.STYLE_SPACING] = '8'
      const styleList = [
        { cguid: 'start', imgUrl: '/images/start.png' },
        { cguid: 'bill', imgUrl: '/images/bill.png' },
        { cguid: 'check', imgUrl: '/images/check.png' },
        { cguid: 'end', imgUrl: '/images/end.png' }
      ]
      for (var i = 0; i < styleList.length; i++) {
        const item = styleList[i]
        const newStyle = mxUtils.clone(style)
        newStyle[mxConstants.STYLE_IMAGE] = item.imgUrl
        graph.getStylesheet().putCellStyle(item.cguid, newStyle)
      }

    },

  }
}